package com.whale.config;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.whale.constants.RoleConstants;
import com.whale.kernel.provider.ServletContextProvider;
import com.whale.kernel.service.HtmlMenuService;
import com.whale.kernel.service.HtmlPageService;
import com.whale.kernel.service.UserService;

public class RefreshListener implements
		ApplicationListener<ContextRefreshedEvent> {

	private Logger logger = LoggerFactory.getLogger(RefreshListener.class);

	private HtmlMenuService htmlMenuService;

	private HtmlPageService htmlPageService;

	private UserService userService;

	private ServletContextProvider servletContextProvider;

	public void setServletContextProvider(
			ServletContextProvider servletContextProvider) {
		this.servletContextProvider = servletContextProvider;
	}

	public void setHtmlMenuService(HtmlMenuService htmlMenuService) {
		this.htmlMenuService = htmlMenuService;
	}

	public void setHtmlPageService(HtmlPageService htmlPageService) {
		this.htmlPageService = htmlPageService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void onApplicationEvent(ContextRefreshedEvent refreshEvent) {
		logger.info("Starting refresh application...");
		htmlMenuService.reInitilizeHtmlMenu(servletContextProvider
				.getServletContext());
		htmlPageService.reInitilizeHtmlPages(servletContextProvider
				.getServletContext());
		userService.createOrUpdateUser("admin", "admin",
				Arrays.asList(RoleConstants.ROLE_ADMIN));
		userService.createOrUpdateUser("user", "user",
				Arrays.asList(RoleConstants.ROLE_USER));
		logger.info("Finished refresh application");
	}

}
